package com.naizhuai.ui.presenter;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.management.presenter.UserSearchDataApiStoreIml;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.ValidateUtil;
import com.naizhuai.util.autocomplete.RecyclerViewPresenter;

import java.util.List;

import rx.Observer;


public class InputUserPhonePresenter extends RecyclerViewPresenter<PersonUserBean> {

    protected Adapter adapter;
    private Context mContext;
    private ViewGroup vgContent;
    private View view;
    private String companyId = null;
    private RequestUserDataListener searchUserDataListener;

    private CharSequence submitMessage = "";

    public InputUserPhonePresenter(Context context) {
        super(context);
        mContext = context;
    }

    public InputUserPhonePresenter(Context context, String companyId) {
        super(context);
        mContext = context;
        this.companyId = companyId;
    }

    @Override
    public void setRequestUserDataListener(RequestUserDataListener searchUserDataListener) {
        this.searchUserDataListener = searchUserDataListener;
    }

    @Override
    protected PopupDimensions getPopupDimensions() {
        PopupDimensions dims = new PopupDimensions();
        dims.width = 600;
        dims.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        return dims;
    }

    @Override
    protected RecyclerView.Adapter instantiateAdapter() {
        adapter = new Adapter();
        return adapter;
    }

    @Override
    protected ViewGroup getView() {
        RelativeLayout relative = new RelativeLayout(mContext);
        vgContent = super.getView();
        relative.addView(vgContent);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        view = inflater.inflate(R.layout.dialog_loading, null);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(600, RelativeLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(params);
        relative.addView(view);
        return relative;
    }

    private void initViewVisibility() {
        vgContent.setVisibility(View.VISIBLE);
        view.setVisibility(View.VISIBLE);
    }

    private void cancelSearchVisibility() {
        view.setVisibility(View.INVISIBLE);
        vgContent.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onQuery(@Nullable CharSequence query) {
        NaizhuAILog.e("CharSequence query=" + query);
        submitMessage = query;
        initViewVisibility();
        if (query != null && ValidateUtil.validateMobile(query.toString())) {
            vgContent.setVisibility(View.INVISIBLE);
            view.setVisibility(View.VISIBLE);
            requestDataFromService(query);
        } else {
            adapter.setData(null);
            view.setVisibility(View.INVISIBLE);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public CharSequence getSubmitMessage() {
        return submitMessage;
    }

    private void requestDataFromService(CharSequence query) {
        Observer<List<PersonUserBean>> observer = new Observer<List<PersonUserBean>>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                NaizhuAILog.e("Throwable=" + e.getMessage());
                if (e instanceof ApiException) {
                    ApiException server = (ApiException) e;
                    DialogUtils.showPromptDialog(mContext, server.getDisplayMessage());
                }
            }

            @Override
            public void onNext(List<PersonUserBean> result) {
                NaizhuAILog.e("result=" + result.toString());
                adapter.setData(result);
                if (result.size() != 0) {
                    cancelSearchVisibility();
                    adapter.notifyDataSetChanged();
                } else {
                    cancelSearchVisibility();
                    adapter.notifyDataSetChanged();
                }

            }
        };
        if (searchUserDataListener == null)
            UserSearchDataApiStoreIml.getInstance().getUserByPhone(companyId, null, query.toString())
                    .subscribe(observer);
        else
            searchUserDataListener.subscribeData(observer,query.toString());
    }


    class Adapter extends RecyclerView.Adapter<Adapter.Holder> {

        private List<PersonUserBean> data;

        public class Holder extends RecyclerView.ViewHolder {
            private View root;
            private LinearLayout contentLayout;
            private TextView username;
            private ImageView headImg;
            private TextView numberNotice;

            public Holder(View itemView) {
                super(itemView);
                root = itemView;
                username = ((TextView) itemView.findViewById(R.id.nick_name));
                contentLayout = ((LinearLayout) itemView.findViewById(R.id.content_layout));
                headImg = ((ImageView) itemView.findViewById(R.id.head_url));
                numberNotice = ((TextView) itemView.findViewById(R.id.number_notice));
            }
        }

        public void setData(List<PersonUserBean> data) {
            this.data = data;
        }

        @Override
        public int getItemCount() {
            return (isEmpty()) ? 1 : data.size();
        }

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(getContext()).inflate(R.layout.adapter_slide_edit_phone_acomplete, parent, false));
        }

        private boolean isEmpty() {
            return data == null || data.isEmpty();
        }

        @Override
        public void onBindViewHolder(Holder holder, int position) {
            if (isEmpty()) {
                if (data == null) {
                    holder.numberNotice.setText(mContext.getResources().getString(R.string.error_phone_number));
                } else {
                    holder.numberNotice.setText(mContext.getResources().getString(R.string.no_user_by_phone));
                }
                holder.contentLayout.setVisibility(View.INVISIBLE);
                holder.numberNotice.setVisibility(View.VISIBLE);
                holder.root.setOnClickListener(null);
                return;
            }
            holder.contentLayout.setVisibility(View.VISIBLE);
            holder.numberNotice.setVisibility(View.INVISIBLE);
            PersonUserBean label = data.get(position);
            holder.username.setText(data.get(position).getNickName());
            ImageUtils.glideThumbViewByUrl(mContext,holder.headImg,data.get(position).getUserLogoUrl());
            holder.root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dispatchClick(label);
                }
            });
        }
    }
}
